<template>
  <div>
    <el-upload action="#" list-type="picture-card" :file-list="fileList" :on-preview="handlePreview" :limit="conut" :class="{disabled}" :on-remove="delRemove" :http-request="handleUplod" :on-change="handlChange" :before-upload="beforeUpload">
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="图片" :visible="visible" @close="visible=false">
      <img :src="imgsrc" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>

<script>
// 引入
import COS from 'cos-js-sdk-v5'
// 导入
const cos = new COS({
  SecretId: 'AKIDBG7k7FFD0ZuxueC6oJWVGn59ze3C8whK', // 身份ID
  SecretKey: 'hKn22pVA5nIemt6KOFuPhmfYWFp8HApJ'// 身份秘钥
})
export default {
  props: {
    conut: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [

      ],
      visible: false,
      imgsrc: ''
    }
  },
  computed: {
    disabled() {
      return this.fileList.length === this.conut
    },
    isAllUpload() {
      return this.fileList.every(item => item.status === '"success"')
    }
  },
  methods: {
    handlePreview(file) {
      this.visible = true
      this.imgsrc = file.url
    },
    delRemove(file, fileList) {
    // 第一种方法删除
      this.fileList = [...fileList]// 数据独立
      // 第二种,过滤
      // this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    // 覆盖默认的上传行为
    handleUplod({ file }) {
      const fileObj = this.fileList.find(item => item.uid === file.uid)
      console.log('fileObj')
      console.log(fileObj)
      // 待上传的文件对象file
      cos.putObject({
        Bucket: 'hrsaas-102-lwq-1314876237', /* 必须 存储桶名称 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: +new Date() + file.name, /* (字符串类型) 必须 上传到腾讯云存储的图片的名称 key保证唯一性*/
        Body: file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          // 处理上传进度条状态
          fileObj.status = 'uploading'
          // 处理上传的进度条百分比值
          fileObj.percentage = parseInt(progressData.percent * 100)
        }
      }, function(err, data) {
        // 成功或失败都执行
        if (err) {
          console.log(err)
        }
        console.log(data)
        fileObj.status = 'success'// 更新状态
        fileObj.url = 'http://' + data.Location// 更新路径
      })
    },
    handlChange(file, fileList) {
      this.fileList = [...fileList]
    },
    beforeUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('文件大小不能超过1M')
        return false
      }
    }
  }

}
</script>

<style lang='scss' scoped>
.disabled{
::v-deep{
.el-upload--picture-card {
  display: none;
}
}
}
</style>
